"""
商品管理API
"""
from flask import Blueprint, request, jsonify, current_app
from flask_jwt_extended import jwt_required, get_jwt_identity
import os
from werkzeug.utils import secure_filename

from app.models.product import Product, ProductVariant, ProductSpecification, ProductStatus
from app.schemas.product import ProductSchema, ProductVariantSchema
from app.extensions import db
from app.utils.auth import admin_required
from app.api import product_bp
from app.models.user import User

@product_bp.route('/', methods=['GET'])
def get_products():
    """获取所有商品"""
    # 默认只返回上架的商品
    status = request.args.get('status', ProductStatus.ACTIVE.value)
    
    query = Product.query
    
    # 如果指定了状态，则按状态筛选
    if status != 'all':
        query = query.filter_by(status=status)
    
    products = query.all()
    result = []
    
    for product in products:
        result.append({
            "id": product.id,
            "name": product.name,
            "description": product.description,
            "price": product.price,
            "stock": product.stock,
            "sku": product.sku,
            "status": product.status,
            "created_at": product.created_at.isoformat() if product.created_at else None
        })
    
    return jsonify(result), 200

@product_bp.route('/<int:product_id>', methods=['GET'])
def get_product(product_id):
    """获取单个商品详情"""
    product = Product.query.get(product_id)
    
    if not product:
        return jsonify({"error": "商品不存在"}), 404
    
    # 获取规格
    specs = []
    for spec in product.specifications:
        specs.append({
            "id": spec.id,
            "name": spec.name,
            "options": spec.option_list
        })
    
    # 获取变体
    variants = []
    for variant in product.variants:
        variants.append({
            "id": variant.id,
            "sku": variant.sku,
            "price": variant.price,
            "stock": variant.stock,
            "specifications": variant.specifications
        })
    
    return jsonify({
        "id": product.id,
        "name": product.name,
        "description": product.description,
        "price": product.price,
        "stock": product.stock,
        "sku": product.sku,
        "status": product.status,
        "created_at": product.created_at.isoformat() if product.created_at else None,
        "specifications": specs,
        "variants": variants
    }), 200

@product_bp.route('', methods=['POST'])
@jwt_required()
@admin_required
def create_product():
    """创建新商品"""
    data = request.get_json()
    
    try:
        product = Product(
            name=data.get('name'),
            description=data.get('description'),
            price=data.get('price'),
            stock=data.get('stock', 0),
            sku=data.get('sku'),
            status=data.get('status', 'active')
        )
        db.session.add(product)
        
        # 处理规格和变体
        if 'specifications' in data:
            for spec_data in data['specifications']:
                spec = ProductSpecification(
                    name=spec_data.get('name'),
                    product=product
                )
                db.session.add(spec)
        
        if 'variants' in data:
            for variant_data in data['variants']:
                variant = ProductVariant(
                    sku=variant_data.get('sku'),
                    price=variant_data.get('price'),
                    stock=variant_data.get('stock', 0),
                    specifications=variant_data.get('specifications', {}),
                    product=product
                )
                db.session.add(variant)
        
        db.session.commit()
        
        return jsonify({
            "msg": "商品创建成功",
            "product": ProductSchema().dump(product)
        }), 201
    except Exception as e:
        db.session.rollback()
        return jsonify({"msg": f"创建商品失败: {str(e)}"}), 500

@product_bp.route('/<int:product_id>', methods=['PUT'])
@jwt_required()
@admin_required
def update_product(product_id):
    """更新商品信息"""
    product = Product.query.get(product_id)
    
    if not product:
        return jsonify({"msg": "商品不存在"}), 404
    
    data = request.get_json()
    
    try:
        if 'name' in data:
            product.name = data.get('name')
        if 'description' in data:
            product.description = data.get('description')
        if 'price' in data:
            product.price = data.get('price')
        if 'stock' in data:
            product.stock = data.get('stock')
        if 'sku' in data:
            product.sku = data.get('sku')
        if 'status' in data:
            product.status = data.get('status')
        
        db.session.commit()
        
        return jsonify({
            "msg": "商品更新成功",
            "product": ProductSchema().dump(product)
        }), 200
    except Exception as e:
        db.session.rollback()
        return jsonify({"msg": f"更新商品失败: {str(e)}"}), 500

@product_bp.route('/<int:product_id>', methods=['DELETE'])
@jwt_required()
@admin_required
def delete_product(product_id):
    """删除商品"""
    product = Product.query.get(product_id)
    
    if not product:
        return jsonify({"msg": "商品不存在"}), 404
    
    try:
        db.session.delete(product)
        db.session.commit()
        return jsonify({"msg": "商品删除成功"}), 200
    except Exception as e:
        db.session.rollback()
        return jsonify({"msg": f"删除商品失败: {str(e)}"}), 500

@product_bp.route('/upload-image', methods=['POST'])
@jwt_required()
@admin_required
def upload_image():
    """上传商品图片"""
    if 'image' not in request.files:
        return jsonify({"msg": "请选择图片文件"}), 400
    
    file = request.files['image']
    
    if file.filename == '':
        return jsonify({"msg": "未选择文件"}), 400
    
    allowed_extensions = {'png', 'jpg', 'jpeg', 'gif'}
    if '.' not in file.filename or file.filename.rsplit('.', 1)[1].lower() not in allowed_extensions:
        return jsonify({"msg": "文件类型不支持"}), 400
    
    try:
        filename = secure_filename(file.filename)
        upload_folder = os.path.join(current_app.config['UPLOAD_FOLDER'], 'products')
        
        # 确保上传目录存在
        if not os.path.exists(upload_folder):
            os.makedirs(upload_folder)
        
        file_path = os.path.join(upload_folder, filename)
        file.save(file_path)
        
        return jsonify({
            "msg": "图片上传成功",
            "filename": filename,
            "url": f"/uploads/products/{filename}"
        }), 200
    except Exception as e:
        return jsonify({"msg": f"图片上传失败: {str(e)}"}), 500 